package ui;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.table.AbstractTableModel;

import bean.User;

public class UserDataModel extends AbstractTableModel {

	private List<User> data;
	public static String[] fields = new String[]{"loginName","name","passWord","phoneNumber","email","score"};
	
	public UserDataModel(List<User> users)
	{
		this.data = users;
	}
	public UserDataModel()
	{
		this.data = new ArrayList<User>();
	}
	public void setData(List<User> users)
	{
		this.data.clear();
		this.data = users;
		this.fireTableDataChanged();
	}
	public void addRecord(User user)
	{
		this.data.add(user);
		this.fireTableDataChanged();
	}
	public void clearData()
	{
		this.data.clear();
		this.fireTableDataChanged();
	}
	public int getColumnCount() {
		return fields.length;
	}

	public int getRowCount() {
		
		return this.data.size();
	}

	public Object getValueAt(int row, int col) {
		User user = data.get(row);
		try {
			return getColumnMethod(col).invoke(user, null);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean isCellEditable(int row, int col){
		if (col == 0)
		{
			return false;
		}else{
			return true; 
		}
	}
	
	
	private Method getColumnMethod(int col)
	{
		String fieldName = fields[col];
		char[] chars = fieldName.toCharArray();
		chars[0]-=32;
		
		try {
			return User.class.getMethod("get" + String.valueOf(chars), null) ;
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
